package zy.blogs.controller;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zy.blogs.entity.ParkingLot;
import zy.blogs.entity.PricingStandard;
import zy.blogs.entity.Vehicle;
import zy.blogs.mapper.VehicleMapper;
import zy.blogs.service.ParkingLotService;
import zy.blogs.service.VehicleService;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Controller
@RequestMapping("/vehicle")
public class VehicleController extends ServiceImpl<VehicleMapper, Vehicle> {

    @Value("${save.path}")
    String savePath;
    private final VehicleService service;
    private final ParkingLotService parkingLotService;
    private VehicleController(VehicleService service,ParkingLotService parkingLotService){
        this.service=service;
        this.parkingLotService=parkingLotService;
    }
    @RequestMapping("/list")
    public String list(Model model){
        List<Vehicle> entities=service.getAll();
        model.addAttribute("list",entities);
        return "/vehicle/list";
    }
    @RequestMapping(value = "/insert")
    public String insert(Model model){
        model.addAttribute("vehicle",new Vehicle());
        List<ParkingLot> parkingLots=parkingLotService.getAll();
        model.addAttribute("parkingLots",parkingLots);
        return "/vehicle/edit";
    }
    @RequestMapping(value = "/edit/{id}")
    public String edit(@PathVariable("id")Long id, Model model){
        Vehicle entity=service.getById(id);
        model.addAttribute("vehicle",entity);
        List<ParkingLot> parkingLots=parkingLotService.getAll();
        model.addAttribute("parkingLots",parkingLots);
        return "/vehicle/edit";
    }

    @RequestMapping(value = "/save",method= RequestMethod.POST)
    public String save(@ModelAttribute("vehicle")Vehicle entity
            , @RequestParam("isActive")boolean isActive
            , @RequestParam("parkingLotId") Long parkingLotId
            , @RequestParam("file")MultipartFile file) throws  Exception{

        entity.setActive(isActive);
        ParkingLot parkingLot=parkingLotService.getById(parkingLotId);
        entity.setParkingLot(parkingLot);

        //上传到指定目录
        String fileName=System.currentTimeMillis()+"-"+file.getOriginalFilename();//生成文件名
        Path saveTo= Paths.get(savePath,fileName);//设置文件存储的路径
        Files.write(saveTo,file.getBytes());//存储文件

        //存储图片URL
        entity.setPicUrl("/images/"+fileName);


        boolean result=entity.getId()!=null?service.update(entity):service.insert(entity);
        return "redirect:/vehicle/list()";
    }

}
